﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcShop.Models;
using MvcShop.Models.Repositories;
using MvcShop.Models.Services;
using MvcShop.Core.Architecture.Cache;
using MvcShop.Models.ViewDataModels;
using MvcShop.Extensions;


namespace MvcShop.MVC.Controllers
{
    [HandleError]
    public class HomeController : BaseController
    {
        #region ==== Fields ====
        private readonly IProductRepository<Product> _productRepository;
        private readonly ICategoryRepository<Category> _categoryRepository;
        private readonly IProductsService _productsService;
        private readonly INewsRepository<News> _newsRepository;
        private readonly IOnlinePollRepository<OnlinePoll> _oPollRepository;
        private IPollOptionRepository<PollOption> _pollOpRepository;
        private IMsCache _msCache;
        #endregion

        #region ==== Constructors ====
        public HomeController(IProductRepository<Product> productRepository,
            ICategoryRepository<Category> categoryRepository,
            IProductsService productsService,
            INewsRepository<News> newsRepository, 
            IOnlinePollRepository<OnlinePoll> oPollRepository, 
            IPollOptionRepository<PollOption> pollOpRepository,
            IMsCache msCache)
        {
            this._productRepository = productRepository;
            this._categoryRepository = categoryRepository;
            this._productsService = productsService;
            this._newsRepository = newsRepository;
            this._oPollRepository = oPollRepository;
            this._pollOpRepository = pollOpRepository;
            this._msCache = msCache;
        }
        #endregion

        #region ==== HomeIndex ====
        [OutputCache(Duration = 3600, Location = System.Web.UI.OutputCacheLocation.Client, VaryByParam="none")]
        public ActionResult Index()
        {

            return View();
        }

        public ActionResult Bargain()
        {
            IEnumerable<FProductList> bar;
            if (!this._msCache.TryGet("BargainProducts", out bar))
            {
                try
                {
                    bar = this._productsService.GetProByKeyWord(new EqualCriteria("Position", 4), 1, 6, new Order(OrderType.DESC, "ShelvesTime"));
                    var _ExpireTime = DateTime.Now.AddDays(1);//指定1天后过期
                    this._msCache.Set<IEnumerable<FProductList>>("BargainProducts", bar, _ExpireTime);
                }
                catch (Exception e)
                {
                    throw new Exception(e.Message);
                }
            }

            return this.PartialView(bar);
        }

        public ActionResult HotSell()
        {
            IEnumerable<FProductList> hs;
            if (!this._msCache.TryGet("HotSellProducts", out hs))
            {
                try
                {
                    hs = this._productsService.GetProByKeyWord(new EqualCriteria("Position", 3), 1, 9, new Order(OrderType.DESC, "SellAmount"));
                    var _ExpireTime = DateTime.Now.AddDays(1);//指定1天后过期
                    this._msCache.Set<IEnumerable<FProductList>>("HotSellProducts", hs, _ExpireTime);
                }
                catch (Exception e)
                {
                    throw new Exception(e.Message);
                }
            }

            return this.PartialView("Bargain", hs);
        }

        [OutputCache(Duration = 3600, Location = System.Web.UI.OutputCacheLocation.Client, VaryByParam = "none")]
        public ActionResult HotNews()
        {
            IEnumerable<NewsList> news;
            if (!this._msCache.TryGet("NewsList", out news))
            {
                try
                {
                    news = this._newsRepository.GetHeadLine(10);
                    var _ExpireTime = DateTime.Now.AddDays(1);//指定1天后过期
                    this._msCache.Set<IEnumerable<NewsList>>("NewsList", news, _ExpireTime);
                }
                catch (Exception e)
                {
                    throw new Exception(e.Message);
                }
            }

            return this.PartialView(news);
        }

        public ActionResult DefaultCategorise()
        {
            var cats = this._categoryRepository.GetCNavigator();
            /*
            IEnumerable<CategoryNavigator> cats;
            if (!this._msCache.TryGet("DefaultCategory", out cats))
            {
                try
                {
                    cats = this._categoryRepository.GetCNavigator();
                    var _ExpireTime = DateTime.Now.AddDays(1);//指定1天后过期
                    this._msCache.Set<IEnumerable<CategoryNavigator>>("DefaultCategory", cats, _ExpireTime);
                }
                catch (Exception e)
                {
                    throw new Exception(e.Message);
                }
            }*/

            return this.PartialView(cats);
        }

        public ActionResult Recommend()
        {
            IEnumerable<ProductList> re;
            if (!this._msCache.TryGet("RecommendProducts", out re))
            {
                try
                {
                    re = this._productsService.GetProductList(new EqualCriteria("Position", 2), 1, 10, new Order(OrderType.DESC, "ProductId"));
                    var _ExpireTime = DateTime.Now.AddDays(1);//指定1天后过期
                    this._msCache.Set<IEnumerable<ProductList>>("RecommendProducts", re, _ExpireTime);
                }
                catch (Exception e)
                {
                    throw new Exception(e.Message);
                }
            }

            return this.PartialView("ProductList", re);
        }

        public ActionResult JustShelves()
        {
            IEnumerable<ProductList> js;
            if (!this._msCache.TryGet("JustShelvesProducts", out js))
            {
                try
                {
                    js = this._productsService.GetProductList(new EqualCriteria("Position", 5), 1, 10, new Order(OrderType.DESC, "ShelvesTime"));
                    var _ExpireTime = DateTime.Now.AddDays(1);//指定1天后过期
                    this._msCache.Set<IEnumerable<ProductList>>("JustShelvesProducts", js, _ExpireTime);
                }
                catch (Exception e)
                {
                    throw new Exception(e.Message);
                }
            }
            return this.PartialView("ProductList", js);
        }

        public ActionResult DefaultOnlinePoll()
        {
            IEnumerable<PollOption> pollOp = null;
            var poll = this._oPollRepository.GetDefault();
            if (poll != null)
            {
                ViewData["Subject"] = poll.Subject;
                ViewData["Selectmode"] = poll.Selectmode.Trim();
                pollOp = this._pollOpRepository.Find(new EqualCriteria("OId", poll.OnlinePollId));
            }

            return this.PartialView(pollOp);
        }

        [HttpPost]
        public ActionResult HeadlePoll(int[] PollOptionId)
        {
            if (!Request.IsAjaxRequest()) return this.RedirectToAction<ErrorController>(c => c.HttpError404("非法请求!"));

            string message;
            bool has = true;
            if (PollOptionId != null)
            {
                try
                {
                    this._pollOpRepository.UpdataBallots(PollOptionId);
                }
                catch
                {
                    has = false;
                }
            }
            else { has = false; }

            message = has ? "提交成功。谢谢您的参与！" : "请选择调查项。";

            return Json(new { Message = message });
        }
        #endregion

        public ActionResult Sitemap()
        {
            return View(SiteMap.RootNode);
        }

        public ActionResult About()
        {
            return View();
        }

        
    }
}
